<template>
  <div>
    <Drawer
      title="患者详情"
      v-model="drawer"
      width="720"
      :mask-closable="false"
      :styles="styles"
    >
      <Form
        :model="createData"
        ref="create"
        :rules="createRules"
        label-position="top"
      >
        <Row :gutter="32">
          <Col span="8">
            <FormItem label="姓名" prop="name">
              <Input v-model="createData.name" :clearable="false" />
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="手机号" prop="mobile">
              <Input v-model="createData.mobile" :clearable="false"></Input>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="微信/QQ号" prop="wx_name">
              <Input v-model="createData.wx_name" clearable></Input>
            </FormItem>
          </Col>
        </Row>
        <div class="hr-row"><span class="hr-row-text">病情信息</span></div>
        <Row :gutter="32">
          <Col span="8">
            <FormItem label="效果类型" prop="effect_type_id">
              <Select v-model="createData.effect_type_id" clearable>
                <Option
                  v-for="item in baseInfo.effect_type_list"
                  :key="item.id"
                  :value="item.id"
                  :disabled="+item.status === 0"
                >
                  {{ item.name }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="16">
            <FormItem label="部位" prop="body_parts_ids">
              <Select
                v-model="createData.body_parts_ids"
                filterable
                multiple
                :max-tag-count="3"
              >
                <Option
                  v-for="item in baseInfo.body_parts_list"
                  :key="item.id"
                  :value="item.id"
                  :disabled="+item.status === 0"
                >
                  {{ item.name }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="16">
            <FormItem label="患者标签" prop="tags_ids">
              <Select
                v-model="createData.tags_ids"
                filterable
                multiple
                :max-tag-count="3"
              >
                <OptionGroup
                  v-for="item in baseInfo.tags_list"
                  :key="item.id"
                  :label="item.name"
                >
                  <Option
                    v-for="items in item.children"
                    :value="items.id"
                    :key="items.id"
                    :disabled="+items.status === 0"
                  >
                    {{ items.name }}</Option
                  >
                </OptionGroup>
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="风控类型" prop="risk_type_id">
              <Select v-model="createData.risk_type_id" clearable>
                <Option
                  v-for="item in baseInfo.risk_type_list"
                  :key="item.id"
                  :value="item.id"
                  :disabled="+item.status === 0"
                >
                  {{ item.name }}</Option
                >
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="32">
          <Col span="8">
            <FormItem label="诊室" prop="clinic_id">
              <Select
                :disabled="disabled"
                v-model="createData.clinic_id"
                :clearable="false"
                @on-change="Belonging"
              >
                <Option
                  v-for="item in baseInfo.clinic_list"
                  :key="item.id"
                  :value="item.id"
                  :disabled="+item.status === 0"
                  >{{ item.name }}
                </Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="8" v-show="medicalType">
            <FormItem label="归属人" prop="belong_assistant_id">
              <Select
                v-model="createData.belong_assistant_id"
                :clearable="false"
              >
                <Option
                  v-for="item in Belonging_list"
                  :key="item.value"
                  :value="item.value"
                  :disabled="+item.status === 0"
                >
                  {{ item.title }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="8" v-show="customerType">
            <FormItem label="归属人" prop="belong_member_id">
              <Select v-model="createData.belong_member_id" :clearable="false">
                <Option
                  v-for="item in baseInfo.member_customer_list"
                  :key="item.id"
                  :value="item.id"
                  :disabled="+item.status === 0"
                >
                  {{ item.name }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
            <!-- <div style="width:100%"></div> -->
            <!-- <FormItem label="就诊类型" prop="outpatient_type_id">
                            <Select disabled v-model="createData.outpatient_type_id" clearable>
                                <Option v-for="item in baseInfo.outpatient_type_list" :key="item.id" :value="item.id">{{ item.name }}</Option>
                            </Select>
                        </FormItem> -->
          </Col>
        </Row>
        <Row :gutter="32">
          <Col span="8">
            <FormItem label="病种" prop="patient_diseases_id">
              <Select
                v-model="createData.patient_diseases_id"
                @on-change="searchList"
                placeholder="一级病种"
                clearable
              >
                <Option
                  v-for="item in baseInfo.patient_diseases_list"
                  :key="item.id"
                  :value="item.id"
                  :disabled="+item.status === 0"
                >
                  {{ item.name }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label=" " prop="patient_diseases_child_id">
              <Select
                v-model="createData.patient_diseases_child_id"
                clearable
                placeholder="二级病种"
              >
                <Option
                  v-for="item in patient_level_list"
                  :key="item.id"
                  :value="item.id"
                  :disabled="+item.status === 0"
                  >{{ item.name }}
                </Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <div class="hr-row"><span class="hr-row-text">完善信息</span></div>
        <Row :gutter="32">
          <Col span="8">
            <FormItem label="生日" prop="birthday">
              <DatePicker
                v-model="createData.birthday"
                type="date"
                placeholder="用户生日"
                @on-change="handleChangeBirthday"
              ></DatePicker>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="年龄" prop="age">
              <InputNumber
                :max="150"
                :min="1"
                v-model="createData.age"
              ></InputNumber>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="职业" prop="profession">
              <Input v-model="createData.profession" clearable></Input>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="性别" prop="gender">
              <RadioGroup v-model="createData.gender">
                <Radio label="1">男</Radio>
                <Radio label="2">女</Radio>
                <Radio label="0">不详</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="患者来源" prop="source_channel_id">
              <Select v-model="createData.source_channel_id" clearable>
                <Option
                  v-for="item in baseInfo.source_channel_list"
                  :key="item.id"
                  :value="item.id"
                  :disabled="+item.status === 0"
                >
                  {{ item.name }}</Option
                >
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="32">
          <Col span="8">
            <FormItem label="城市" prop="city_id">
              <Select
                v-model="createData.city_id"
                placeholder="请输入城市拼音简写"
                filterable
                remote
                clearable
                :remote-method="handleQueryText"
                :loading="queryLoading"
              >
                <Option
                  v-for="item in city_list"
                  :key="item.id"
                  :value="item.key"
                  :disabled="+item.status === 0"
                  >{{ item.name }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="16">
            <FormItem label="详细地址" prop="address">
              <Input v-model="createData.address" clearable></Input>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="32" v-if="false">
          <Col span="8" v-if="customerType">
            <FormItem label="客服归属人" prop="belong_member_id">
              <Select v-model="createData.belong_member_id" clearable>
                <Option
                  v-for="item in baseInfo.member_customer_list"
                  :key="item.id"
                  :value="item.id"
                  :disabled="+item.status === 0"
                >
                  {{ item.name }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="微信昵称" prop="nickname">
              <Input v-model="createData.nickname" clearable></Input>
            </FormItem>
          </Col>
          <Col span="8" v-if="customerType">
            <FormItem label="客服下次回访日期" prop="kf_next_callback_time">
              <DatePicker
                :options="options"
                v-model="createData.kf_next_callback_time"
                type="date"
              >
              </DatePicker>
            </FormItem>
          </Col>
          <Col span="8" v-if="medicalType">
            <FormItem label="医助下次回访日期" prop="yz_next_callback_time">
              <DatePicker
                :options="options"
                v-model="createData.yz_next_callback_time"
                type="date"
              >
              </DatePicker>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="下次复诊日期" prop="next_revisiting_time">
              <DatePicker
                :options="options"
                v-model="createData.next_revisiting_time"
                type="date"
              >
              </DatePicker>
            </FormItem>
          </Col>
          <Col span="24">
            <FormItem label="备注" prop="remark">
              <Input
                type="textarea"
                v-model="createData.remark"
                :rows="4"
                placeholder="请输入备注内容"
              />
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div class="demo-drawer-footer">
        <Button style="margin-right: 8px" @click="handleDrawerCancel"
          >取消</Button
        >
        <Button type="primary" @click="handleDrawer">保存</Button>
      </div>
    </Drawer>
  </div>
</template>

<script>
import { PatientUpdataDetail, PatientUpdata, searchCity } from "@/api/patient";
import { getSecondLevel, GetClinicMember } from "@/api/setting";
import dayjs from "dayjs";
export default {
  name: "editPatient",
  data() {
    const validateMobile = (rule, value, callback) => {
      let number= value.replace(/^\s+|\s+$/g,"")
      if (number === "") {
        callback(new Error("请输入手机号码"));
      } else {
        let reg = /^1[3456789]\d{9}$/;
        
        if (!reg.test(number)) {
            callback(new Error("请输入正确的手机号码"));
        }else{
            callback();
        }
      }
    };
    return {
      drawer: false,
      queryLoading: false,
      city_list: [],
      formData: {
        personnel: [],
        Occupation: "",
        Effect: "",
        risk: "",
        Diagnosis: "",
      },
      options: {
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 86400000;
        },
      },
      patientId: "",
      customerType: false,
      medicalType: false,
      createData: {
        id: "",
        name: "",
        birthday: "",
        age: 0,
        nickname: "",
        wx_name: "",
        source_channel_id: "",
        gender: "0",
        mobile: "",
        city_id: "",
        address: "",
        patient_diseases_id: "",
        patient_diseases_child_id: "",
        body_parts_ids: [],
        tags_ids: [],
        belong_member_id: "",
        belong_assistant_id: "",
        effect_type_id: [],
        risk_type_id: [],
        clinic_assess_id: [],
        outpatient_type_id: [],
        clinic_id: "",
        profession: "",
        kf_next_callback_time: "",
        yz_next_callback_time: "",
        next_revisiting_time: "",
        remark: "",
      },
      styles: {
        height: "calc(100% - 55px)",
        overflow: "auto",
        paddingBottom: "53px",
        position: "static",
      },
      createRules: {
        name: [{ required: true, message: "请输入患者名称", trigger: "blur" }],
        mobile: [{ validator: validateMobile, trigger: "blur" }],
      },
      baseInfo: {
        member_customer_list: [],
        source_channel_list: [],
        patient_diseases_list: [],
        body_parts_list: [],
        tags_list: [],
        member_list: [],
        effect_type_list: [],
        risk_type_list: [],
        clinic_assess_list: [],
        outpatient_type_list: [],
        clinic_list: [],
        Belonging_list: [],
      },
      editType: 1, // 1 客服编辑  2 患者(医助)编辑
      patient_level_list: [],
      Belonging_list: [],
      is_change_clinic: 1,
      disabled: true,
      isShow: false,
      belong: {},
      belongStatus: true,
    };
  },
  methods: {
    handleOpenDrawer(id, editType) {
      this.editType = editType;
      this.$refs["create"].resetFields();
      this.drawer = true;
      this.belongStatus = true;
      this.patientId = id;
      PatientUpdataDetail({ id, edit_type: editType }).then((res) => {
        this.is_change_clinic = res.is_change_clinic;
        this.belong = Object.assign({}, res);
        if (this.is_change_clinic === 1) {
          this.disabled = false;
        }
        this.Belonging_list = [];
        this.createData.belong_assistant_id = res.belong_assistant_id;
        // this.baseInfo = res.condition
        for (let key in this.baseInfo) {
          if (res.condition[key]) {
            this.baseInfo[key] = res.condition[key];
          } else {
            this.baseInfo[key] = [];
          }
        }
        res.is_show_customer === 1
          ? (this.customerType = true)
          : (this.customerType = false);
        res.is_show_medical === 1
          ? (this.medicalType = true)
          : (this.medicalType = false);
        for (let key in this.createData) {
          this.createData[key] = res[key];
        }
        if (res.city_name && res.city_name !== "") {
          if (res.city_id !== "0") {
            this.createData.city_id = res.city_id + res.city_name;
          } else {
            this.createData.city_id = "";
          }
        } else {
          if (res.city_id === "0") {
            res.city_id = "";
          }
        }
        this.getSecondList(this.createData.patient_diseases_id);
        this.getBelonging(res.clinic_id);
      });
    },
    // 查找字符串
    handleQueryText(query) {
      if (query !== "") {
        if (parseFloat(query).toString() !== "NaN")
          query = query.slice(6, query.length);
        this.queryLoading = true;
        return new Promise((resolve) => {
          setTimeout(() => {
            searchCity({
              keywords: query,
            }).then((res) => {
              if (res.list && res.list.length > 0) {
                const list = res.list.map((item) => {
                  return {
                    key: item.id + query,
                    id: item.id,
                    name: item.name,
                  };
                });
                this.city_list = list;
              }
              resolve(res.data);
            });
            this.queryLoading = false;
          }, 200);
        });
      }
      // let name = query
      // if (query !== '') {
      //     if (parseFloat(name).toString() !== 'NaN') name = name.slice(6, name.length)
      //     this.queryLoading = true;
      //     return new Promise(resolve => {
      //         setTimeout(() => {
      //             searchCity({
      //                 keywords: name
      //             }).then(res => {
      //                 if (res.list && res.list.length > 0) {
      //                     const list = res.list.map(item => {
      //                         return {
      //                             key: item.id + item.name,
      //                             id: item.id,
      //                             name: item.name
      //                         }
      //                     })
      //                     this.city_list = list
      //                 }
      //                 resolve(res.data)
      //             })
      //             this.queryLoading = false
      //         }, 200)
      //     })
      // }
    },
    // 监听时间
    handleChangeBirthday(e) {
      if (e !== "") {
        this.createData.age = dayjs().format("YYYY") - dayjs(e).format("YYYY");
      }
    },
    handleDrawerCancel() {
      this.drawer = false;
    },
    handleDrawer() {
      this.$refs.create.validate((valid) => {
        if (valid) {
          let sendData = JSON.parse(JSON.stringify(this.createData));
          sendData.edit_type =
            this.customerType === true && this.medicalType === true
              ? 3
              : this.customerType === true
              ? 1
              : 2;
          sendData.id = this.patientId;
          sendData.edit_type = this.editType;
          sendData.city_id && sendData.city_id !== ""
            ? (sendData.city_id = sendData.city_id.slice(0, 6))
            : (sendData.city_id = "");
          sendData.body_parts_ids =
            sendData.body_parts_ids.length > 0
              ? sendData.body_parts_ids.join(",")
              : "";
          sendData.tags_ids =
            sendData.tags_ids.length > 0 ? sendData.tags_ids.join(",") : "";
          sendData.birthday =
            sendData.birthday !== undefined && sendData.birthday !== ""
              ? dayjs(sendData.birthday).format("YYYY-MM-DD")
              : "";
          sendData.kf_next_callback_time =
            sendData.kf_next_callback_time !== "" &&
            sendData.kf_next_callback_time !== undefined
              ? dayjs(sendData.kf_next_callback_time).format("YYYY-MM-DD")
              : "";
          sendData.yz_next_callback_time =
            sendData.yz_next_callback_time !== "" &&
            sendData.yz_next_callback_time !== undefined
              ? dayjs(sendData.yz_next_callback_time).format("YYYY-MM-DD")
              : "";
          sendData.next_revisiting_time =
            sendData.next_revisiting_time !== "" &&
            sendData.next_revisiting_time !== undefined
              ? dayjs(sendData.next_revisiting_time).format("YYYY-MM-DD")
              : "";
          PatientUpdata(sendData).then(() => {
            this.drawer = false;
            this.$Message.success("编辑成功");
            this.$emit("ok");
          });
        }
      });
    },
    // 触发获取二级病种
    searchList(id = "") {
      this.createData.patient_diseases_child_id = "";
      this.patient_level_list = [];
      this.getSecondList(id);
    },
    // 获取二级病种
    getSecondList(id = "") {
      if (id === "") return false;
      const config = { patient_diseases_id: id };
      getSecondLevel(config)
        .then((res) => {
          this.patient_level_list = res.list || [];
        })
        .catch(() => {});
    },
    Belonging(id = "") {
      if (!this.belongStatus) {
        this.createData.belong_assistant_child_id = "";
        this.createData.belong_assistant_id = "";
        this.Belonging_list = [];
        this.getBelonging(id);
      }
    },
    // 归属人
    getBelonging(id = "") {
      const config = {
        clinic_id: id,
        edit_type: this.editType,
      };
      GetClinicMember(config)
        .then((res) => {
          // this.createData.belong_assistant_id = this.belong.belong_assistant_id
          this.Belonging_list = res;
        })
        .finally(() => {
          this.belongStatus = false;
        });
    },
  },
};
</script>

<style scoped>
/deep/.ivu-form-label-top .ivu-form-item-label {
  min-height: 24px;
}

/deep/.ivu-form-label-top .ivu-date-picker {
  vertical-align: top;
}

/deep/.ivu-drawer-mask {
  z-index: 1200;
}

/deep/.ivu-drawer-wrap {
  z-index: 1200;
}
</style>
